package cn.ticsmyc.tools.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例工厂
 * @author Ticsmyc
 * @date 2020-10-29 21:44
 */
public class SingletonFactory {
    private volatile static Map<Class,Object> objectCache;

    private SingletonFactory(){}

    public static <T> T getSingletonInstance(Class<T> clazz){
        if(objectCache == null){
            init();
        }
        Object instance = objectCache.get(clazz);
        if(instance == null){
            synchronized (SingletonFactory.class){
                if(instance == null){
                    try {
                        instance = clazz.newInstance();
                        objectCache.put(clazz,instance);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException(e.getMessage(),e);
                    }
                }
            }
        }
        return clazz.cast(instance);
    }

    private static void init(){
        synchronized (SingletonFactory.class){
            if(objectCache == null){
                objectCache =new ConcurrentHashMap<>();
            }
        }
    }

}
